<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class SMS {
function waitEndChar($oSocket,$endChar=">") {
    while(1) {
        $c = fgetc($oSocket);
        if (($c == $endChar)) {
            break;
        }
    }
}
function getStamp(){
        list($Mili, $bot) = explode(" ", microtime());
        $DM=substr(strval($Mili),2,4);
        return strval(date("Y")."-".date("m")."-".date("d")." ".date("H").":".date("i").":".date("s").".".$DM);
    }
function waitStr($oSocket,$str,$waitPrompt=false,$endChar=">") {
    $readed = "";
    if ($str != "") {
        while (1) {
            $char = fgetc($oSocket);
            $c = trim($char,"\n\r");	
            if ($c != "") {
                $readed .= $c;
                if ($readed == $str) {
                    if ($waitPrompt) {
                        $this->waitEndChar($oSocket,$endChar);	
                        break;
                    }
                    break;
                }
            } else {
                $readed = "";
            }
        }
    } else {
        $this->waitEndChar($oSocket,$endChar);	
    }
}
    function send($destination, $text) {

    $strHost = "10.3.1.7";
    $strPort = "8323";
    $errno=0;
    $errstr=0;
    echo "inicio".$this->getStamp();
    $oSocket = fsockopen ($strHost, $strPort, $errno, $errstr, 20);
        if (!$oSocket) {
            echo "$errstr ($errno)<br>\n";
            exit($errno);
        } else {
            $this->waitStr($oSocket,"username: ");
            
            fputs($oSocket, "voip\r\n");
            
            $this->waitStr($oSocket,"password: *");
            
            fputs($oSocket, "1234\r\n");
            $this->waitStr($oSocket,"****");
            

            fputs($oSocket, "module1\r");
            $this->waitStr($oSocket,"module1");
            
            sleep(2);

            fputs($oSocket, "ate1\r");
            $this->waitStr($oSocket,"0");
            

            fputs($oSocket, "at+cmgf=1\r");
            $this->waitStr($oSocket,"0");
            

            fputs($oSocket, "at+cmgs=\"" .$destination."\"\r");
            $this->waitStr($oSocket,"",true);
            

            fputs($oSocket, $text);
            fputs($oSocket, chr(26));
            $this->waitStr($oSocket,"0");
            

            fclose($oSocket);

            sleep(4);
        }
    }
}